const app = {

	 ApiUrl: 'https://xjtuboshu.cn/api/',//测试
	request: function(url, data, type='GET') {
		let temp = data
	
		
/*
状态码200成功  400失败  410000 请登陆  410001 登陆已过期 410002登陆状态有误  410003 账号已禁用
*/ 
		var str = app.gets('token')? app.gets('token'):'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJtYXJtb3QuZGlkdTg2LmNvbSIsImF1ZCI6Im1hcm1vdC5kaWR1ODYuY29tIiwiaWF0IjoxNjE4MjE1Nzc1LCJuYmYiOjE2MTgyMTU3NzUsImV4cCI6MTYxODgyMDU3NSwianRpIjp7ImlkIjoxLCJ0eXBlIjoid2VjaGF0In19.JmynIGY5tvQaGagcno058tLXswBpdd4zgb4giZ_9hlE'
		var promise = new Promise((resolve, reject) => {
			uni.request({
				url: app.ApiUrl + url,
				data: temp,
				header:{
					"Authori-zation":'Bearer '+ str
				},
				method: type,
				success: (res) => {
					
					if (res.data.status == 200) {
						resolve(res.data);
					} else if(res.data.status==400) {
						
						app.toast(res.data.msg)
						// if(res.data.code == 401){
						// 	app.nto('login/login')
						// }
					}else if(res.data.status==410001){
						app.save('token','')
						app.confirm('登录已过期，请重新登录',(res)=>{
							app.nto('login')
						},()=>{})
					}else if(res.data.status==410000){
						app.toast(res.data.msg)
						app.save('token','')
					}
				},
				fail(e) {
					app.toast('网络异常')
					console.log(e)
					reject(e)
				}
			})
		})
		return promise
	},
	  stampToDate:function(time) {
	        var date = new Date(Number(time*1000));//将接收到的的String类型的时间转为数字类型
	        var y = date.getFullYear();
	        var m = date.getMonth() + 1;
	        var d = date.getDate();
	        var hour = date.getHours().toString();
	        var minutes = date.getMinutes().toString();
	        var seconds = date.getSeconds().toString();
	        if(hour < 10) {
	            hour = "0" + hour;
	        }
	        if(minutes < 10) {
	            minutes = "0" + minutes;
	        }
	        if(seconds < 10) {
	            seconds = "0" + seconds;
	        }
	        return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " " + hour + ":" + minutes + ":" + seconds;
	    },


	toast: function(title, duration = 1500) {
		uni.showToast({
			title,
			duration,
			icon: 'none'
		});
	},
	getlocation:function(callback){
	

		uni.getLocation({
					    type: 'gcj02',
						geocode:true,//设置该参数为true可直接获取经纬度及城市信息
					    success: function (res) {
							app.save('longitude',res.longitude)
							app.save('latitude',res.latitude)
							let obj = {
								longitude:res.longitude,
								latitude:res.latitude
							}
							callback(obj)
					    },
						fail: function (err) {
							console.log(err)
							// uni.showToast({
							//     title: '获取地址失败，将导致部分功能不可用',
							// 	icon:'none'
							// });
						}
				})		
	},
	// 上传图片的接口参数
  getuploadinfo:function(dir,callback){
		let data ={
				dir,
			}
		
		app.request('getGetkey', data).then(res => {
			callback(res.data)
			
		})
	
	},
	
	upload:function(uploadinfo,callback) {
					let that = this;
					uni.chooseImage({
						count: 5, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], //从相册选择
						success: function(res) {
						
							var imageSrc = res.tempFilePaths[0]
							// if(res.tempFiles[0].type.indexOf('gif') != -1){
							// 	app.toast('头像不允许上传gif')
							// 	return
							// }
							
							  var tempFilesSize = res.tempFiles[0].size
						
							let pos = imageSrc.lastIndexOf('.');
							let filename = imageSrc.substring(0, pos) // 文件名
							let extendName = imageSrc.substring(pos + 1); // 扩展名
							let stroeAs = uploadinfo.dir  +   parseInt(Math.random()*1000) +'xrzww' + new Date().getTime()    + '.' + 'png';
							app.load('图片上传中...');
						
							uni.uploadFile({
								url: uploadinfo.host,
								filePath: imageSrc,
								fileType:'image',
								name: 'file',
								formData: {
									'key': stroeAs,
									'policy': uploadinfo.policy,
									'OSSAccessKeyId': uploadinfo.accessid,
									'success_action_status': '200', //让服务端返回200,不然，默认会返回204
									'signature':uploadinfo.signature,
								},
								
								success(res) {
									uni.hideLoading();
									uni.showToast({
										title: '上传成功',
										icon: 'success',
										duration: 1000
									})
									
										var test = '/'+stroeAs
									
								
									var sendavatar = '/'+stroeAs
									callback( sendavatar)
									
								},
								fail:function(res){
									console.log(res)
								}
							})
						},
						fail() {
							uni.showToast({
								title: '取消选择图片',
								icon: 'none',
								duration: 2000
							});
						}
					});
				},
	// 上传成功返回的图片路径
	
	
	
	// 将file传给后端，返回图片
	fileupload:function(callback,url='api/upload/image'){
		uni.chooseImage({
		    count: 6, //默认9
		    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		    sourceType: ['album'], //从相册选择
		    success: function (res) {
				app.load('正在上传中...')
				let filePaths = res.tempFilePaths
				uni.uploadFile({
				    url:app.ApiUrl+url,     // 后端api接口
				    filePath: filePaths[0], // uni.chooseImage函数调用后获取的本地文件路劲
				    name:'file',     //后端通过'file'获取上传的文件对象
				    success:(response) => {
						 app.hide()
						var res = JSON.parse(response.data)
				      if(res.status==200){
						  callback(res.data.url)
					  }else{
						  app.toast(res.msg)
					  }
				    }
				});
			
				// app.request('api/upload/image',data,"POST").then(res=>{
				// 	console.log(res,'图片路径')
				// })
		    }
		})
	},
	load: function(title = '加载中...') {
		uni.showLoading({
			title,
		})
	},
	hide: function() {
		uni.hideLoading()
	},
	nto: function(url, id) {
		
			
		if (id) {
			
			uni.navigateTo({
				url: '/pages/' + url + '?id=' + id
			})
		} else {
			uni.navigateTo({
				url: '/pages/' + url
			})
		}
		
	},

	back:function(){
		uni.navigateBack({                       
			    delta: 1
			});
	},
	ntobj: function(url, obj) {
	
			uni.navigateTo({
				url: '/pages/' + url + '?data=' + JSON.stringify(obj)
			})
			
		
			
	
	},
	snto:function(url,id){
		if (id) {
			uni.switchTab({
					url: '/pages/' + url + '?id=' + id
			})
		} else {
			uni.switchTab({
				url: '/pages/' + url
			})
		}
	},
	confirm: function(content, submit, cancel, title = '提示') {
		uni.showModal({
			title,
			content,
			success: function(res) {
				if (res.confirm) {
					submit(res)
				} else if (res.cancel) {
					cancel(res)
				}
			}
		});
	},
	isphoneNumber: function(tel) {
		var reg = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
		return reg.test(tel);

	},
	save: function(key, data) {
		uni.setStorage({
			key,
			data,
			success: function() {

			}
		});
	},
	gets: function(key) { 
		
	return	uni.getStorageSync(key)
		
	},
	timeago: function(timestamp) { //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
		   var dateTimeStamp=new Date(timestamp*1000).getTime()
		          
		  
		          var minute = 1000 * 60;
		          var hour = minute * 60;
		          var day = hour * 24;
		          
		          var month = day * 30;
		          var year=month*12;
		          var now = new Date().getTime();
		          var diffValue = now - dateTimeStamp;
		          var result=""
		          if(diffValue < 0) {
		              return;
		          }
		          
		  
		          var monthC = diffValue / month;
		          var weekC = diffValue / (7 * day);
		          var dayC = diffValue / day;
		          var hourC = diffValue / hour;
		          var minC = diffValue / minute;
		          var yearC=diffValue / year
		          if(yearC>=1){
		              return  "" + parseInt(yearC) + "年前";
		          }
		          if(monthC >= 1) {
		              result = "" + parseInt(monthC) + "月前";
		          } else if(weekC >= 1) {
		              result = "" + parseInt(weekC) + "周前";
		          } else if(dayC >= 1) {
		              result = "" + parseInt(dayC) + "天前";
		          } else if(hourC >= 1) {
		              result = "" + parseInt(hourC) + "小时前";
		          } else if(minC >= 1) {
		              result = "" + parseInt(minC) + "分钟前";
		          } else{
		              result = "刚刚";
		          }
		          
		          return result;
	},
	 randomSort:function(a,num){
			    var arr = a,
			        random = [],
			        len = arr.length;
			    for (var i = 0; i < len; i++) {
			      var index = Math.floor(Math.random()*(len - i));
			      random.push(a[index]);
			      arr.splice(index,1);
			    }
				if(num){
					return random.splice(0,num);
				}else{
					return random.splice(0,3)
				}
			  }


}
export default app
